home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 3046 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.1 KB  |  78 lines

  1. Path: longwood.cs.ucf.edu!not-for-mail
  2. From: schnitzi@longwood.cs.ucf.edu (Mark Schnitzius)
  3. Newsgroups: comp.lang.c
  4. Subject: Sorting large files
  5. Date: 25 Jan 1996 13:48:11 -0500
  6. Organization: University of Central Florida
  7. Message-ID: <4e8j9b$cuf@longwood.cs.ucf.edu>
  8. NNTP-Posting-Host: longwood.cs.ucf.edu
  9.  
  10. There was some discussion here a little while
  11. back on how to sort the lines in a large file
  12. without having to have a huge character array.
  13. I suggested using ftell and fseek to hunt down
  14. the particular lines you are comparing.  Only
  15. just the other day did I notice (via a web
  16. search engine) that someone posted a question
  17. on how this could be done...  So here goes.
  18.  
  19.  
  20. This program sorts stdin to stdout, so it would
  21. have to be run like this:
  22.  
  23.     sort < infile > outfile
  24.  
  25. It should be easy enough to modify to use file
  26. pointers, though.  It also requires a 'long'
  27. for every line in the file, but this beats the
  28. heck out of a huge character array.  I've 
  29. written it here to handle up to 5000-line files.
  30.  
  31.  
  32. #include <stdio.h>
  33.  
  34. main()
  35. {
  36.         long index[5000], z;
  37.  
  38.         char line1[ 256 ], line2[ 256 ];
  39.  
  40.         int i, j, count=0;
  41.  
  42.         do
  43.         {
  44.                 index[ count++ ] = ftell( stdin );
  45.         }
  46.         while ( gets(line1) );
  47.  
  48.         for ( i=0; i<count-1; i++ )
  49.         {
  50.                 for ( j=i+1; j<count; j++ )
  51.                 {
  52.                         fseek( stdin, index[i], 0 );
  53.                         gets( line1 );
  54.                         fseek( stdin, index[j], 0 );
  55.                         gets( line2 );
  56.  
  57.                         if ( strcmp( line1, line2 ) > 0 )
  58.                         {
  59.                                 z = index[i];
  60.                                 index[i] = index[j];
  61.                                 index[j] = z;
  62.                         }
  63.                 }
  64.         }
  65.  
  66.         for ( i=0; i<count; i++ )
  67.         {
  68.                 fseek( stdin, index[i], 0 );
  69.                 gets( line1 );
  70.                 puts( line1 );
  71.         }
  72. }
  73.  
  74.  
  75. _____________________________________________________________
  76. mark schnitzius - - - - - - - - - - - - - schnitzi@mentos.com
  77. - - - -<a href="http://east.isx.com/~schnitzi/">me</a>- - - -
  78.